package com.alipay.app.groupmeal.standard.ui.b.util;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.base.BaseObserver;
import com.alipay.app.groupmeal.standard.base.BaseResObserver;
import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.bean.FoodBean;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.constant.SystemConsts;
import com.alipay.app.groupmeal.standard.http.RetrofitHelper;
import com.alipay.app.groupmeal.standard.http.bean.resp.AliOrderDTO;
import com.alipay.app.groupmeal.standard.http.bean.resp.HexiaoOrderModel;
import com.alipay.app.groupmeal.standard.http.bean.resp.QrPayModel;
import com.alipay.app.groupmeal.standard.http.bean.resp.QuerySignResp;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.http.bean.resp.WithholdResp;
import com.alipay.app.groupmeal.standard.http.bean.resp.WithholdValidateResp;
import com.alipay.app.groupmeal.standard.offline.bean.FkBean;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.iot.sdk.APIManager;
import com.alipay.sdk.util.LogUtil;
import com.alipay.sdk.util.NetUtils;
import com.alipay.sdk.util.cloudsaleapi.CloudSaleApiUtil;
import com.alipay.sdk.util.cloudsaleapi.bean.QuerySignBizContentReq;
import com.alipay.sdk.util.cloudsaleapi.bean.WithholdReq;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;

public class WIth {

    public interface WithResult {

        void onSuccess(WithholdResp withholdResp);

        void onOfflineFace(String amount);

        void onFail(String code, String msg);

        void onUnknown();

        //补支付
        void onStartPayment(float amount, String outTradeNo);
    }

    private BaseMVCActivity activity;
    private String amount;
    private String uid;
    private String authCode;
    private boolean isFace = true;//刷脸或扫码
    private String senceNo;
    private boolean isSecret;
    private WithResult withResult;
    private OrderBean orderBean;
    private final String appId = ConfigConstant.withholdAppId;
    private final String merchantAppId = ConfigConstant.withholdMerchantAppId;

    public WIth(BaseMVCActivity activity) {
        this.activity = activity;
    }

    public WIth setAmount(String amount) {
        this.amount = amount;
        return this;
    }

    public WIth setUid(String uid) {
        this.uid = uid;
        return this;
    }

    public WIth setAuthCode(String authCode) {
        this.authCode = authCode;
        return this;
    }

    public WIth isFace(boolean isFace) {
        this.isFace = isFace;
        return this;
    }

    public WIth setWithResult(WithResult withResult) {
        this.withResult = withResult;
        return this;
    }

    public WIth setSecret(boolean secret) {
        this.isSecret = secret;
        return this;
    }

    public WIth setOrderBean(OrderBean orderBean) {
        this.orderBean = orderBean;
        return this;
    }

//
//    /**
//     * 联机微信付款码
//     *
//     * @param authCode
//     * @param price
//     */
//    public void scanWeiXinQrPay(String authCode, String price, BlockingBaseObserver<Result<String>> observer) {
//        RetrofitHelper.getInstance().weixinPay(authCode, price)
//                .compose(RxUtils.rxSchedulerHelper(activity.lifecycleProvider))
//                .subscribeWith(observer);
//
//    }

    public void uploadOrder(String amount, String tradeNo, Date createTime, String authCode, String cardno,
                            BlockingBaseObserver<Result<String>> observer) {
        RetrofitHelper.getInstance().upLoadOrder(amount, tradeNo, createTime, authCode, cardno).subscribeWith(observer);
    }


    public void toQrPay(String price, String authCode, String order,
                        BlockingBaseObserver<Result<QrPayModel>> observer) {
        RetrofitHelper.getInstance().toQrPay(price, authCode, order).subscribeWith(observer);
    }


    public void checkQrOrders(String order,
                              BlockingBaseObserver<Result<QrPayModel>> observer) {
        RetrofitHelper.getInstance().checkQrOrders(order).subscribeWith(observer);
    }


    public void cardHexiao(String cardsn,
                           BlockingBaseObserver<Result<HexiaoOrderModel>> observer) {
        RetrofitHelper.getInstance().cardHexiao(cardsn)
                .compose(RxHelper.rxSchedulerHelper()).subscribeWith(observer);
    }


    public void getPosInit( ) {
        RetrofitHelper.getInstance().deviceSign()
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(new BaseResObserver<String>(activity) {

                    @Override
                    public void doNext(String resp) {
                        System.out.println("请求返回" + resp);
                        SystemConsts.getSystemConsts().setPosnum(resp);
                    }

                    @Override
                    public void doError(String code, String msg) {

                    }
                });
    }

//    public void startWith() {
//        if (ConfigConstant.isWithHold) {
//            if (!isSecret && isFace) {
//                //无网络的时候,同一个用户本地无未同步的订单,则保存到本地直接放行
//                if (!NetUtils.isNetSystemUsable(activity)) {
//                    OrderBean order = new OrderBean();
//                    order.setHavePost(false);
//                    order.setAmount(amount);
//                    order.setUid(uid);
//                    order.setAuthCode(authCode);
//                    OrderDataManager.getInstance().insert(order);
//                    LogUtil.d("无网络,保存订单到本地: " + order.toString());
//                    if (withResult != null)
//                        withResult.onOfflineFace(amount);
//                    return;
//                }
//            }
//            //商户代扣
//            querySign();
//        } else {
//            //当面付
//            facePay();
//        }
//    }


    /**
     * 查询签约号
     */
//    private void querySign() {
//        QuerySignBizContentReq bizContentReq = CloudSaleApiUtil.getQuerySignBizContent(uid);
//        RetrofitHelper.getInstance().querySign(bizContentReq, appId, merchantAppId)
//                .compose(RxHelper.rxSchedulerHelper())
//                .subscribeWith(new BaseObserver<QuerySignResp>(activity) {
//
//                    @Override
//                    public void doNext(QuerySignResp resp) {
//                        if (TextUtils.isEmpty(resp.agreement_no) || resp.agreement_no.equalsIgnoreCase("null")) {
//                            //优先代扣策略,没有签约的就走当面付
//                            if (!isSecret) {
//                                facePay();
//                            } else {
//                                updateOrderFail("NO_AGREEMENT");
//                            }
//                        } else {
//                            //有签约的走代扣
//                            withholdValidate();
//                        }
//                    }
//
//                    @Override
//                    public void doError(String code, String msg) {
//                        if (!isSecret) {
//                            facePay();
//                        } else {
//                            //同步订单,没有签约的用户订单
//                            updateOrderFail(msg);
//                        }
//                    }
//                });
//    }


    public void readCard(String cardSn, BlockingBaseObserver<Result<FkBean>> observer) {

        RetrofitHelper.getInstance().readCard(cardSn)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);

    }

    public void cardPay(String price,
                        String cardsn, String tradeNo,
                        String sessionId, BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().cardPay(price, cardsn, tradeNo, sessionId)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void cardPayV2(String price,
                          String cardsn, String tradeNo,
                          String sessionId, int onLine, Date createTime, BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().cardPayV2(price, cardsn, tradeNo, sessionId, onLine, new LinkedList<>(), createTime)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void cardPayV2(String price,
                          String cardsn, String tradeNo,
                          String sessionId, int onLine, List<FoodBean> foodBeanList, BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().cardPayV2(price, cardsn, tradeNo, sessionId, onLine, foodBeanList, new Date())
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void qrPayV2(String price,
                        String auth, String orders, String terminalParams, List<FoodBean> foodBeanList, BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().qrPayV2(price, auth, orders, terminalParams, foodBeanList)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void cardPayRule() {

    }

    /**
     * 在线人脸支付
     *
     * @param price
     * @param tradeNo
     * @param sessionId
     * @param observer
     */
    public void facePay(String price, String tradeNo, String sessionId,
                        String faceToken, String aliUid, String terminalParams,
                        BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().facePay(price, faceToken, aliUid, tradeNo, sessionId, terminalParams)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void getCensus(BlockingBaseObserver<Result<JSONObject>> observer) {
        RetrofitHelper.getInstance().getCensus().compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void getOder(BlockingBaseObserver<Result<List<AliOrderDTO>>> observer) {
        RetrofitHelper.getInstance().getOder().compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void facePayV2(String price, String tradeNo, String sessionId,
                          String faceToken, String aliUid, String terminalParams,
                          List<FoodBean> foodBeanList,
                          BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().facePayV2(price, faceToken, aliUid, tradeNo, sessionId, terminalParams, foodBeanList)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }

    public void checkOrder(String deviceOrders,BlockingBaseObserver<Result<JSONObject>> observer) {
        RetrofitHelper.getInstance().checkOrder(deviceOrders).compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }
    public void hexiao1(String authCode, String faceToken,
                        String aliUid,
                        String tradeNo, String sessionId, String terminalParams,
                        BlockingBaseObserver<Result<AliPayResVo>> observer) {
        RetrofitHelper.getInstance().hexiao1(authCode, faceToken, aliUid, tradeNo, sessionId, terminalParams)
                .compose(RxHelper.rxSchedulerHelper())
                .subscribeWith(observer);
    }


    /**
     * 当面付
     */
//    private void facePay() {
//        LogUtil.d("开始当面付");
//        //当面付
//        withhold(getFacePayBizContent());
//    }

    /**
     * 代扣前校验
     */
//    private void withholdValidate() {
//        WithholdReq.BizContent bizContent = getWithholdBizContent();
//        RetrofitHelper.getInstance()
//                .withholdValidate(bizContent, appId, merchantAppId)
//                .compose(RxHelper.rxSchedulerHelper())
//                .subscribeWith(new BaseObserver<WithholdValidateResp>(activity) {
//
//                    @Override
//                    public void doNext(WithholdValidateResp withholdValidateResp) {
//                        if (withholdValidateResp.pass) {
//                            if (!isFace && TextUtils.isEmpty(uid)) {
//                                uid = withholdValidateResp.user_id;
//                                senceNo = withholdValidateResp.sence_no;
//                            }
//                            //无待支付订单
//                            //商户代扣
//                            withhold(bizContent);
//                        } else {
//                            //有待支付订单
//                            if (withholdValidateResp.failType.equals("WAIT_PAY")) {
//                                if (isSecret) {
//                                    //同步订单的放行,不做拦截
//                                    withhold(bizContent);
//                                    return;
//                                }
//                                if (withResult != null)
//                                    withResult.onStartPayment(withholdValidateResp.bizInfo.totalAmount, withholdValidateResp.bizInfo.outTradeNo);
//                            } else {
//                                if (isSecret) {
//                                    updateOrderFail(withholdValidateResp.failType);
//                                    return;
//                                }
//                                String msg = "代扣校验失败";
//                                if (withholdValidateResp.failType.equals("NO_AGREEMENT")) {
//                                    msg = "该用户未签约";
//                                }
//                                //失败页面
//                                if (withResult != null)
//                                    withResult.onFail("", msg);
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void doError(String code, String msg) {
//
//                    }
//                });
//    }

    /**
     * 代扣
     */
//    private void withhold(WithholdReq.BizContent bizContent) {
//        LogUtil.d("代扣商品信息: ", bizContent.goods_detail);
//        RetrofitHelper.getInstance()
//                .withhold(bizContent, appId, merchantAppId)
//                .compose(RxHelper.rxSchedulerHelper())
//                .subscribeWith(new BaseObserver<WithholdResp>(activity) {
//                    @Override
//                    public void doNext(WithholdResp withholdResp) {
//                        if (withholdResp.pay_result.equals("SUCCESS")) {
//                            if (isSecret) {
//                                orderBean.setSuccess(true);
//                                orderBean.setHavePost(true);
//                                OrderDataManager.getInstance().update(orderBean);
//                                return;
//                            }
//                            if (withResult != null)
//                                withResult.onSuccess(withholdResp);
//                        } else {
//                            if (isSecret) {
//                                updateOrderFail(withholdResp.sub_msg);
//                                return;
//                            }
//                            if (withResult != null) {//支付失败
//                                withResult.onFail(withholdResp.sub_code, (TextUtils.isEmpty(withholdResp.sub_msg) ? (TextUtils.equals(withholdResp.msg, "Success") ? "失败" : withholdResp.msg) : withholdResp.sub_msg));
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void doError(String code, String msg) {
//                        if (isSecret) {
//                            updateOrderFail(msg);
//                            return;
//                        }
//                        if (!TextUtils.isEmpty(msg)) {
//                            //支付失败
//                            if (withResult != null)
//                                withResult.onFail(code, msg);
//                        } else {
//                            //支付未知
//                            if (withResult != null)
//                                withResult.onUnknown();
//                        }
//                    }
//                });
//    }

    /**
     * 商户代扣 bizContent
     *
     * @return
     */
//    private WithholdReq.BizContent getWithholdBizContent() {
//        String terminalParams = APIManager.getInstance().getPaymentAPI().signWithDelegated(authCode);
//        return CloudSaleApiUtil.getWithholdBizContent(amount,
//                uid,
//                ConfigConstant.terminalId,
//                authCode,
//                terminalParams,
//                ConfigConstant.sysServicePartnerId,
//                "货柜消费",
//                senceNo,
//                isFace);
//    }

    /**
     * 当面付 bizContent
     *
     * @return
     */
    private WithholdReq.BizContent getFacePayBizContent() {
        String terminalParams = APIManager.getInstance().getPaymentAPI().signWithFaceToken(authCode, String.valueOf(amount));
        return CloudSaleApiUtil.getFacePayBizContent(amount,
                uid,
                ConfigConstant.terminalId,
                authCode,
                terminalParams,
                ConfigConstant.sysServicePartnerId,
                "货柜消费",
                isFace);
    }

    private void updateOrderFail(String errorType) {
        orderBean.setSuccess(false);
        orderBean.setHavePost(true);
        orderBean.setErrorType(errorType);
        OrderDataManager.getInstance().update(orderBean);
        LogUtil.i("订单同步失败,更新本地数据" + orderBean.toString());
    }

    private void updateOrder(OrderBean orderBean) {

    }


}
